package Test.MQ.死信队列回滚超时订单;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class RabbitMQStockRollback {

    private final static String QUEUE_NAME = "order_queue";
    private final static String DLX_NAME = "order_dlx";
    private final static String DLQ_NAME = "order_dlq";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            // 声明死信交换器和死信队列
            channel.exchangeDeclare(DLX_NAME, "direct", true);
            channel.queueDeclare(DLQ_NAME, true, false, false, null);
            channel.queueBind(DLQ_NAME, DLX_NAME, DLQ_NAME);

            // 设置队列参数，包括死信交换器
            Map<String, Object> argsMap = new HashMap<>();
            argsMap.put("x-dead-letter-exchange", DLX_NAME);
            argsMap.put("x-message-ttl", 60000); // 设置消息TTL为60秒
            channel.queueDeclare(QUEUE_NAME, true, false, false, argsMap);

            // 设置消费者处理死信队列中的消息
            channel.basicConsume(DLQ_NAME, true, (consumerTag, message) -> {
                String body = new String(message.getBody(), "UTF-8");
                System.out.println("Received from DLQ: " + body);
                // 回滚库存逻辑
                rollbackStock(body);
            }, consumerTag -> {
            });

            // 生产消息到订单队列
            String message = "Order ID: 12345";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println("Sent: " + message);
        }
    }

    private static void rollbackStock(String message) {
        // 实现库存回滚逻辑
        System.out.println("Rolling back stock for: " + message);
    }
}
